{% extends "前端/template.html" %}

{% block title %}
图片转文本
{% endblock %}

{% block css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
    .container {
        max-width: 900px;
        margin: 30px auto;
        padding: 30px;
        background: #fff;
        border-radius: 15px;
        box-shadow: 0 0 20px rgba(0,0,0,0.1);
    }
    .ai-header {
        text-align: center;
        margin-bottom: 30px;
        color: #2c3e50;
    }
    .ai-header h2 {
        font-size: 2.2rem;
        margin-bottom: 15px;
        background: linear-gradient(45deg, #2c3e50, #3498db);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    .ai-description {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 10px;
        margin-bottom: 25px;
        border-left: 4px solid #3498db;
    }
    .upload-area {
        border: 2px dashed #3498db;
        padding: 30px;
        text-align: center;
        margin-bottom: 25px;
        cursor: pointer;
        border-radius: 12px;
        background: #f8f9fa;
        transition: all 0.3s ease;
    }
    .upload-area:hover {
        border-color: #2980b9;
        background: #edf2f7;
    }
    .upload-area i {
        font-size: 40px;
        color: #3498db;
        margin-bottom: 10px;
    }
    .preview-image {
        max-width: 100%;
        max-height: 400px;
        margin: 15px 0;
        display: none;
        border-radius: 8px;
        box-shadow: 0 0 15px rgba(0,0,0,0.1);
    }
    .result-text {
        width: 100%;
        min-height: 200px;
        margin-top: 25px;
        padding: 15px;
        border: 1px solid #e0e0e0;
        border-radius: 8px;
        font-size: 16px;
        line-height: 1.6;
        background: #fff;
    }
    .loading {
        display: none;
        margin: 20px 0;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 8px;
    }
    .btn-primary {
        background: #3498db;
        border: none;
        padding: 12px 30px;
        font-size: 16px;
        border-radius: 8px;
        transition: all 0.3s ease;
    }
    .btn-primary:hover {
        background: #2980b9;
        transform: translateY(-2px);
    }
    .form-control {
        padding: 12px;
        border-radius: 8px;
        border: 1px solid #e0e0e0;
    }
    .features-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin: 30px 0;
    }
    .feature-item {
        text-align: center;
        padding: 20px;
        background: #f8f9fa;
        border-radius: 10px;
        transition: all 0.3s ease;
    }
    .feature-item:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .feature-item i {
        font-size: 24px;
        color: #3498db;
        margin-bottom: 10px;
    }
    .model-header {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }
    
    .model-list {
        flex: 1 1 250px;
    }
    
    .create-model-btn {
        flex: 0 0 auto;
        white-space: nowrap;
        background: #2ecc71;
        color: white;
        border: none;
        padding: 12px 20px;
        border-radius: 8px;
        transition: all 0.3s ease;
        font-weight: 500;
    }
    
    .create-model-btn:hover {
        background: #27ae60;
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(46, 204, 113, 0.3);
    }
    
    .modal-content {
        border-radius: 15px;
        border: none;
    }
    
    .modal-header {
        background: #f8f9fa;
        border-radius: 15px 15px 0 0;
        border-bottom: 1px solid #eee;
    }
    
    .modal-footer {
        background: #f8f9fa;
        border-radius: 0 0 15px 15px;
        border-top: 1px solid #eee;
    }
    
    @media (max-width: 768px) {
        .container {
            margin: 15px;
            padding: 20px;
        }
        
        .ai-header h2 {
            font-size: 1.8rem;
        }
        
        .features-grid {
            grid-template-columns: 1fr;
        }
        
        .model-header {
            flex-direction: column;
            align-items: stretch;
        }
        
        .model-list {
            margin-bottom: 10px;
        }
        
        .create-model-btn {
            width: 100%;
        }
        
        .upload-area {
            padding: 20px;
        }
        
        .btn-primary {
            width: 100%;
            margin-top: 10px;
        }
    }
    
    /* 美化滚动条 */
    .result-text::-webkit-scrollbar {
        width: 8px;
    }
    
    .result-text::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }
    
    .result-text::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }
    
    .result-text::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
    
    /* 加载动画美化 */
    .loading {
        text-align: center;
        padding: 30px;
        border-radius: 12px;
        background: linear-gradient(145deg, #f8f9fa, #ffffff);
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    }
    
    .loading .spinner-border {
        width: 3rem;
        height: 3rem;
        margin-bottom: 15px;
    }
    
    .loading p {
        color: #666;
        margin: 0;
    }
    
    /* 按钮禁用状态美化 */
    .btn-primary:disabled {
        background: #95a5a6;
        transform: none;
        cursor: not-allowed;
    }
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="ai-header">
        <h2>AI智能图片文字识别</h2>
        <p class="lead">基于先进AI模型的智能文字识别系统</p>
    </div>

    <div class="ai-description">
        <h5><i class="fas fa-robot"></i> AI增强识别</h5>
        <p>本系统采用先进的AI模型进行图片文字识别，不仅能准确提取图片中的文字，还能通过AI模型进行智能纠错和优化，提供更准确的识别结果。</p>
    </div>

    <div class="features-grid">
        <div class="feature-item">
            <i class="fas fa-magic"></i>
            <h6>AI智能纠错</h6>
            <p>自动修正识别错误</p>
        </div>
        <div class="feature-item">
            <i class="fas fa-language"></i>
            <h6>多语言支持</h6>
            <p>支持多种语言识别</p>
        </div>
        <div class="feature-item">
            <i class="fas fa-tachometer-alt"></i>
            <h6>快速处理</h6>
            <p>高效的识别速度</p>
        </div>
    </div>

    <div class="form-group mb-4">
        <div class="model-header">
            <div class="model-list">
                <label for="dialogueId"><i class="fas fa-project-diagram"></i> 选择AI模型：</label>
                <select class="form-control" id="dialogueId">
                    <option value="">请先创建模型</option>
                </select>
            </div>
            <button class="create-model-btn" data-bs-toggle="modal" data-bs-target="#createModelModal">
                <i class="fas fa-plus"></i> 创建新模型
            </button>
        </div>
    </div>

    <div class="upload-area" id="uploadArea">
        <i class="fas fa-cloud-upload-alt"></i>
        <p>点击或拖拽图片到此处上传</p>
        <small class="text-muted">支持jpg、png、jpeg等常见图片格式</small>
        <input type="file" id="fileInput" accept="image/*" style="display: none;">
    </div>

    <img id="previewImage" class="preview-image" alt="预览图片">
    
    <div class="text-center">
        <button class="btn btn-primary" id="submitBtn" disabled>
            <i class="fas fa-wand-magic-sparkles"></i> 开始AI识别
        </button>
    </div>

    <div class="loading">
        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">AI处理中...</span>
        </div>
        <p><i class="fas fa-cog fa-spin"></i> AI正在智能识别中，请稍候...</p>
    </div>

    <textarea class="result-text" id="resultText" readonly placeholder="AI识别结果将在这里显示"></textarea>
</div>

<!-- 创建模型的模态框 -->
<div class="modal fade" id="createModelModal" tabindex="-1" aria-labelledby="createModelModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModelModalLabel">
                    <i class="fas fa-robot"></i> 创建新的AI模型
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="modelName">
                        <i class="fas fa-tag"></i> 模型名称
                    </label>
                    <input type="text" class="form-control" id="modelName" placeholder="请输入模型名称">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="btn btn-primary" id="createModelBtn">
                    <i class="fas fa-check"></i> 创建
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const previewImage = document.getElementById('previewImage');
        const submitBtn = document.getElementById('submitBtn');
        const resultText = document.getElementById('resultText');
        const loading = document.querySelector('.loading');

        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        // 处理拖拽
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#666';
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ccc';
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.style.borderColor = '#ccc';
            const files = e.dataTransfer.files;
            if (files.length > 0 && files[0].type.startsWith('image/')) {
                handleFile(files[0]);
            }
        });

        // 处理文件选择
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFile(e.target.files[0]);
            }
        });

        // 处理文件预览
        function handleFile(file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                previewImage.src = e.target.result;
                previewImage.style.display = 'block';
                // 只有当选择了模型且上传了图片时才启用提交按钮
                const dialogueId = document.getElementById('dialogueId').value;
                submitBtn.disabled = !dialogueId;
            };
            reader.readAsDataURL(file);
        }

        // 提交识别请求
        submitBtn.addEventListener('click', async () => {
            const dialogueId = document.getElementById('dialogueId').value;
            if (!dialogueId) {
                alert('请先创建并选择一个模型');
                return;
            }

            const file = fileInput.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('dialogue_id', dialogueId);
            formData.append('img_file', file);

            try {
                loading.style.display = 'block';
                submitBtn.disabled = true;
                resultText.value = '';

                const response = await fetch('/api/ocr/line1/start_dialogue/', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                if (result.code === 200) {
                    resultText.value = result.data;
                } else {
                    alert('识别失败：' + result.message);
                }
            } catch (error) {
                alert('请求出错：' + error.message);
            } finally {
                loading.style.display = 'none';
                submitBtn.disabled = false;
            }
        });

        // 加载保存的模型列表
        loadSavedModels();

        // 创建模型按钮点击事件
        document.getElementById('createModelBtn').addEventListener('click', async function() {
            const modelName = document.getElementById('modelName').value.trim();
            if (!modelName) {
                alert('请输入模型名称');
                return;
            }

            try {
                const response = await fetch(`/api/ocr/line1/create_dialogue/?model_name=${encodeURIComponent(modelName)}`, {
                    method: 'GET'
                });

                const result = await response.json();
                if (result.code === 200) {
                    // 保存新模型到localStorage
                    saveModel(result.data.model_id, result.data.model_name);
                    // 更新下拉框
                    addModelToSelect(result.data.model_id, result.data.model_name);
                    // 关闭模态框
                    const modal = bootstrap.Modal.getInstance(document.getElementById('createModelModal'));
                    modal.hide();
                    // 清空输入框
                    document.getElementById('modelName').value = '';
                    // 显示成功消息
                    alert('模型创建成功！');
                } else {
                    alert('创建失败：' + result.message);
                }
            } catch (error) {
                alert('请求出错：' + error.message);
            }
        });

        // 加载保存的模型列表
        function loadSavedModels() {
            const savedModels = JSON.parse(localStorage.getItem('aiModels') || '[]');
            const select = document.getElementById('dialogueId');
            
            // 清空现有选项
            select.innerHTML = '';
            
            // 如果没有保存的模型，显示提示选项
            if (savedModels.length === 0) {
                const defaultOption = document.createElement('option');
                defaultOption.value = '';
                defaultOption.textContent = '请先创建模型';
                select.appendChild(defaultOption);
                // 禁用提交按钮
                submitBtn.disabled = true;
            } else {
                // 添加保存的模型
                savedModels.forEach(model => {
                    addModelToSelect(model.id, model.name);
                });
            }
        }

        // 保存模型到localStorage
        function saveModel(modelId, modelName) {
            const savedModels = JSON.parse(localStorage.getItem('aiModels') || '[]');
            savedModels.push({
                id: modelId,
                name: modelName
            });
            localStorage.setItem('aiModels', JSON.stringify(savedModels));
        }

        // 添加模型到下拉框
        function addModelToSelect(modelId, modelName) {
            const select = document.getElementById('dialogueId');
            
            // 如果是第一个模型，清除"请先创建模型"的提示
            if (select.options.length === 1 && select.options[0].value === '') {
                select.innerHTML = '';
            }
            
            const option = document.createElement('option');
            option.value = modelId;
            option.textContent = modelName;
            select.appendChild(option);
            // 选中新创建的模型
            select.value = modelId;
        }

        // 监听模型选择变化
        document.getElementById('dialogueId').addEventListener('change', function() {
            // 当有文件上传时，根据是否选择了模型来启用/禁用提交按钮
            const hasFile = fileInput.files.length > 0;
            submitBtn.disabled = !this.value || !hasFile;
        });
    });
</script>
{% endblock %}

{% block nav_left %}
{% include "前端/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% block footer %}
    {% include "前端/components/Footer.html" %}
{% endblock %}